# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
from django_logs.models import AccessLog
from django_logs.models import Site
import logging
import re
import httpagentparser
import os
import os.path
import time
import log_parser

# Get an instance of a logger
logger = logging.getLogger(__name__)

def index(request):
	template = loader.get_template('django_logs/index.html')
	context = Context({'Sitename': 'Log Analyzer',})
	return HttpResponse(template.render(context))

def reports(request):
	allsites = Site.objects.all()
	template = loader.get_template('django_logs/site_reports.html')
	context = Context({'allsites': allsites,})
	return HttpResponse(template.render(context))
	
def ips(request):
	#allreports = AccessLog.objects.order_by('date_time')[:20]
	allreports = AccessLog.objects.values('ip_address').distinct()
	template = loader.get_template('django_logs/ips.html')
	context = Context({'allreports': allreports,})
	return HttpResponse(template.render(context))

def sites(request):
	allsites = Site.objects.all()
	template = loader.get_template('django_logs/sites.html')
	context = Context({'allsites': allsites,})
	return HttpResponse(template.render(context))
	
def sitesdetails(request, siteId):
	allreports = AccessLog.objects.filter(site=siteId)
	site = Site.objects.get(id=siteId)
	r404 = AccessLog.objects.filter(response_code=404,site=siteId)
	r200 = AccessLog.objects.filter(response_code=200,site=siteId)
	r50x = AccessLog.objects.filter(response_code=50,site=siteId)
	template = loader.get_template('django_logs/SiteDetails.html')
	context = Context({'allreports': allreports,'r404':r404,'r200':r200,'r50x':r50x, 'site': site})
	return HttpResponse(template.render(context))

def reportdetails(request, siteId):
	site = Site.objects.get(id=siteId)
	r404 = AccessLog.objects.filter(response_code=404,site=siteId)
	r200 = AccessLog.objects.filter(response_code=200,site=siteId)
	r50x = AccessLog.objects.filter(response_code=50,site=siteId)
	piechart_values = [len(r404), len(r200),len(r50x)]
	template = loader.get_template('django_logs/ReportDetails.html')
        print piechart_values
	context = Context({'r404':r404,'r200':r200,'r50x':r50x, 'site': site, 'piechart_values' : piechart_values})
	return HttpResponse(template.render(context))

def create_site(request):
	site = Site(name="site9",file_name="site9.ll")
        site.save()
	logger.error('something went wrong!')
	print site
	allsites = Site.objects.all()
        template = loader.get_template('django_logs/sites.html')
        context = Context({'allsites': allsites,})
        return HttpResponse(template.render(context))

def populate_access_log(request):
	global os
        access_log_file = request.GET.get('log_file')
	sitename = request.GET.get('site_name')
#	basename = os.path.split(access_log_file)

	print sitename
	print access_log_file
	exists = os.path.isfile(access_log_file)
 	if(not exists):
		logger.error('Error in reading the file')

#	if(not basename[1]):
#		logger.error('Error in getting the filename ') 
#		return
#        sitename = basename[1].split('_access.log')

	regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) (\d+) "(.*?)" "(.*?)"'

	for line in open(access_log_file):
#	      print line
 	      matches = re.match(regex, line)
	      if matches is not None:
		 try: 	
        	    groups = matches.groups()
	            ip = groups[0]
	            date_time = groups[1]
		    #remove the timezone from the time stamp. We are not intrested in that 
		    s = date_time.split()
                    t=time.strptime(s[0],"%d/%b/%Y:%H:%M:%S")
                    epoch_time = round(time.mktime(t))
	            request = groups[2]
        	    split = request.split()
	            request_method = split[0]
	            request_uri = split[1]
	            http_version = split[2]
	            response_code = groups[3]
	            size = groups[4]
	            referer = groups[5]
	            user_agent = groups[6]
	            operating_sys = log_parser.get_os(user_agent)
	            dist = log_parser.get_dist(user_agent)
	            dist_version = log_parser.get_dist_version(user_agent)
	            browser = log_parser.get_browser_name(user_agent)
	            browser_version = log_parser.get_browser_version(user_agent)
		    log_parser.insert_access_log_entry(sitename, access_log_file, ip, epoch_time, request_method, request_uri, response_code, size, referer, operating_sys, dist, dist_version, browser, browser_version, user_agent)
#	            print '{0} {1} {2} {3} {4}'.format( operating_sys, dist , dist_version , browser, browser_version)
		 except(RuntimeError, TypeError, NameError):
		    pass
	return HttpResponse("Successfully imported access logs")
